<template>
  <div class="canvas-container">
    <div class="header">
      <!-- <div>
      <el-button size="mini" @click="jumpTo(index-2)">上一页</el-button>
      <el-button size="mini" @click="jumpTo(index+2)">下一页</el-button>
      <el-button size="mini" @click="exportImg">导出为图片</el-button>
      </div> -->
      <div class="control">
        <div class="control-button" @click="showCatalogue">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="showThumbnail">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="autoPagerChrome()">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="jumpTo(1)">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="jumpTo(index - 2)">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="page">
          <!-- <input
            type="number"
            v-model="index"
            min="1"
            :max="pages"
            @change="jumpTo(index)"
          /><span>/{{ pages }}</span> -->
          <input
            type="text"
            v-model="indexPage"
            @focus="inputFocus"
            @blur="inputBlur"
          />
        </div>
        <div class="control-button" @click="jumpTo(index + 2)">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="jumpTo(pages)">
          <img
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="audio = !audio">
          <img
            v-show="audio"
            style="pointer-events: none"
            class="fouer"
            src=""
          />
          <img
            v-show="!audio"
            style="pointer-events: none"
            src=""
            alt=""
          />
        </div>
        <div class="control-button" @click="fullScreen()">
          <img
            src=""
            alt=""
          />
        </div>
        <el-button
          style="position: absolute; right: 16px"
          size="mini"
          @click="exportImg"
          >导出为图片</el-button
        >
      </div>
      <div v-if="wjName">
        <!-- <span class="information">页码：{{ index }}/{{ pages }}</span> -->
        <span>文件名称：{{ wjName }}</span>
      </div>
    </div>
    <div id="flipbook">
      <canvas v-for="page in pages" :key="page" :id="'the-canvas' + page">
      </canvas>
    </div>
    <div v-show="thumbnail" id="thumbnail">
      <img
        src=""
        alt=""
        @click="scrollLeft"
      />
      <div class="thumbnail-container">
        <div
          v-for="(item, i) in imgArr"
          :class="['thumbnail-item', i * 2 + 1 == index ? 'checked-item' : '']"
          :key="i"
          @click="thumbnailJump(i)"
        >
          <img v-for="img in item" :src="img" alt="" :key="img" />
        </div>
      </div>
      <img
        src=""
        alt=""
        @click="scrollRight"
      />
    </div>
    <div
      :class="['catalogue', catalogueForShow ? 'catalogueForShow' : '']"
    ></div>
    <audio
      preload="none"
      controls="controls"
      hidden
      src="~@/assets/file/turnBook.mp3"
      id="turnBook"
    ></audio>
  </div>
</template>

<script>
import * as PDFJS from 'pdfjs-dist/legacy/build/pdf'
import workerSrc from 'pdfjs-dist/legacy/build/pdf.worker.entry'
PDFJS.workerSrc = workerSrc
import $ from 'jquery'
import turn from './turn.js'
import JSZip from 'jszip'
const FileSaver = require('file-saver')
export default {
  data() {
    return {
      src: '',
      wjName: '',
      pages: 0,
      index: 1,
      indexPage: '',
      copy: '',
      status: false,
      audio: true,
      autoPage: false,
      autoFc: null,
      height: 0,
      imgArr: [],
      thumbnail: false,
      catalogue: false,
      catalogueForShow: false,
    }
  },
  watch: {
    src: {
      handler: function (val, old) {
        if (val) {
          this._loadFile(val)
        }
      },
    },
  },
  created() {
    let url = this.$route.query.url
    let fileName = this.$route.query.fileName
    this.src = url
    this.wjName = fileName
  },
  mounted() {
    this.windowResize()
    document.onkeydown = (e) => {
      const key = e.keyCode
      if (key == 13) {
        this.jumpTo(this.indexPage, true)
      }
    }
  },
  destroyed() {
    this.clearResize()
    document.onkeydown = null
    window.clearInterval(this.autoFc)
  },
  methods: {
    showCatalogue() {
      this.catalogueForShow = !this.catalogueForShow
    },
    scrollTo(num) {
      if (this.thumbnail) {
        const container = document.querySelector('.thumbnail-container')
        const childrens = container.querySelectorAll('.thumbnail-item')
        const index = Math.floor(num / 2)
        const target = childrens[index]
        const left = target.offsetLeft
        container.scrollLeft = left
      }
    },
    scrollLeft() {
      const container = document.querySelector('.thumbnail-container')
      const item = container.querySelector('.thumbnail-item')
      const width = item.clientWidth
      container.scrollLeft += width * 1.5
    },
    scrollRight() {
      const container = document.querySelector('.thumbnail-container')
      const item = container.querySelector('.thumbnail-item')
      const width = item.clientWidth
      container.scrollLeft -= width * 1.5
    },
    thumbnailJump(val) {
      let num = val * 2 + 1
      this.jumpTo(num)
    },
    showThumbnail() {
      this.thumbnail = !this.thumbnail
    },
    clearResize() {
      window.onresize = null
    },
    windowResize() {
      window.onresize = () => {
        return (() => {
          location.reload()
        })()
      }
    },
    fullScreen() {
      let res = this.$store.getters.fullScreenGetter
      this.$store.dispatch('setFullScreen', !res)
      res = this.$store.getters.fullScreenGetter
      if (res) {
        this.clearResize()
        this.launchFullScreen()
      } else {
        this.exitFullscreen()
      }
    },
    launchFullScreen() {
      let element = document.documentElement
      if (element.requestFullscreen) {
        element.requestFullscreen()
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen()
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen()
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen()
      }
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      }
      setTimeout(() => {
        this.windowResize()
      }, 2000)
    },
    autoPagerChrome() {
      this.autoPage = !this.autoPage
      this.$message.info(this.autoPage ? '开启自动播放' : '关闭自动播放')
      //一直触发
      this.autoFc = window.setInterval(() => {
        if (!this.autoPage) {
          //删除定时器
          window.clearInterval(this.autoFc)
          return
        }
        this.jumpTo(this.index + 2)
      }, 5000)
    },
    inputFocus() {
      this.status = true
      this.copy = this.indexPage
      this.indexPage = ''
    },
    inputBlur() {
      this.status = false
      this.indexPage = this.copy
    },
    jumpTo(index, boolean) {
      if (this.status && boolean) {
        if (!/^\d+$/.test(index)) {
          this.indexPage = ''
          return
        }
      }
      if (index > this.pages) {
        $('#flipbook').turn('page', this.pages)
        return
      }
      $('#flipbook').turn('page', index)
    },
    playAudio() {
      if (this.audio) {
        var turnBook = document.getElementById('turnBook')
        turnBook.play()
      }
    },
    _renderPage(num) {
      this.pdfDoc.getPage(num).then((page) => {
        let canvas = document.getElementById('the-canvas' + num)
        var vp = page.getViewport({ scale: 1 })
        let ctx = canvas.getContext('2d')
        let dpr = window.devicePixelRatio || 1
        let bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1
        let ratio = dpr / bsr
        let container = document.querySelector('.canvas-container')
        let viewport = page.getViewport({
          // scale: container.clientWidth / vp.width,
          scale: 1,
        })
        canvas.width = Math.floor(viewport.width * ratio)
        canvas.height = Math.floor(viewport.height * ratio)
        this.height = canvas.height
        canvas.style.width = Math.floor(viewport.width) + 'px'
        canvas.style.height = Math.floor(viewport.height) + 'px'
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
        let renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        }
        let pageRender = page.render(renderContext)
        pageRender.promise.then(() => {
          let img = canvas.toDataURL('image/png', 1.0)
          this.imgArr.some((item, index) => {
            if (index == 0 && item.length == 0) {
              item.push(img)
              return true
            }
            if (item.length < 2 && index != 0) {
              item.push(img)
              return true
            }
          })
        })
        if (this.pages > num) {
          this._renderPage(num + 1)
        } else {
          this.onTurn()
        }
      })
    },
    _loadFile(url) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      PDFJS.getDocument(url).promise.then((pdf) => {
        loading.close()
        this.pdfDoc = pdf
        this.pages = this.pdfDoc.numPages
        this.$nextTick(() => {
          this._renderPage(1)
        })
      })
    },
    onTurn() {
      let that = this
      const width = document.querySelector('.canvas-container').clientWidth
      const pages = this.pages
      const nums = Math.ceil((pages + 0.1) / 2)
      for (let i = 0; i < nums; i++) {
        this.imgArr.push([])
      }
      this.$nextTick(() => {
        $('#flipbook').turn({
          autoCenter: true,
          height: that.height,
          width: width,
          pages: pages,
          when: {
            turning: () => {
              this.playAudio()
            },
            turned: (e, page, view) => {
              this.index =
                view[view.length - 1] != 0 ? view[view.length - 1] : view[0]
              this.indexPage = `${this.index}/${this.pages}`
              this.scrollTo(this.index)
            },
            // last: (e, page, view) => {
            //   this.$message.info("已经是最后一页了");
            // },
          },
        })
      })
    },
    splitBase64(dataurl) {
      var arr = dataurl.split(',')
      return arr[1]
    },
    exportImg() {
      this.clearResize()
      let zip = new JSZip() //创建一个JSZip实例
      let images = zip.folder('images') //创建一个文件夹用来存放图片
      //遍历canvas，将其生成图片放进文件夹images中
      const newArr = this.imgArr.flat()
      newArr.forEach((item, index) => {
        images.file('photo-' + (index + 1) + '.png', this.splitBase64(item), {
          base64: true,
        })
      })
      // $("canvas").each((index, ele) => {
      //   let canvas = document.querySelector("#the-canvas2" + (index + 1));
      //   if (canvas) {
      //     //将图片放进文件夹images中
      //     //参数1为图片名称，参数2为图片数据（格式为base64，需去除base64前缀 data:image/png;base64）
      //     images.file(
      //       "photo-" + (index + 1) + ".png",
      //       this.splitBase64(canvas.toDataURL("image/png", 1.0)),
      //       {
      //         base64: true,
      //       }
      //     );
      //   }
      // });
      //打包下载
      zip
        .generateAsync({
          type: 'blob',
        })
        .then(function (content) {
          FileSaver.saveAs(content, 'picture.zip') //saveAs依赖的js文件是FileSaver.js
        })
      this.windowResize()
    },
  },
}
</script>

<style scoped lang="scss">
.canvas-container {
  width: 100%;
  height: 100%;
  position: relative;
  // height: 800px;
  background: rgb(247, 248, 249);
  padding: 5px 0;
  // overflow-y: auto;
  // display: flex;
  // flex-wrap: wrap;
  // justify-content: center;
  // canvas {
  //   margin: 0 auto;
  // }
  .header {
    text-align: center;
    .control {
      width: 100%;
      height: 46px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: rgb(44, 127, 153);
      box-shadow: rgb(24, 107, 133) 0px 1px 2px;
      .control-button {
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }
      }
      .page {
        span {
          color: white;
          margin-left: 4px;
        }
        input {
          width: 45px;
          text-align: center;
        }
      }
    }
    .information {
      margin-right: 16px;
    }
  }
  #thumbnail {
    bottom: 0;
    width: 100%;
    height: 110px;
    padding: 5px;
    position: absolute;
    display: flex;
    // border: 1px solid gray;
    align-items: center;
    justify-content: center;
    img {
      width: 26px;
      height: 52px;
      cursor: pointer;
    }
    .thumbnail-container {
      width: 80%;
      height: 90px;
      display: flex;
      margin: 0 10px;
      overflow-x: auto;
      .thumbnail-item {
        margin-right: 10px;
        // position: relative;
        &:hover {
          // box-shadow: 1px 1px 1px gray;
          border: 2px solid #016baf;
        }
        // &::before{
        //   content: "";
        //   width: 100%;
        //   height: 100%;
        //   background: rgba(0, 0, 0, 0.2);
        //   position:absolute;
        //   left: 0;
        //   top:0;
        // }
        img {
          height: 75px;
          width: 100px;
        }
      }
    }
    .checked-item {
      border: 2px solid #016baf;
      // &::before{
      //   position: relative;
      // }
    }
  }
  .catalogue {
    position: absolute;
    touch-action: none;
    user-select: none;
    -webkit-user-drag: none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    background-color: rgb(36, 101, 122);
    color: rgb(255, 255, 255);
    height: 727px;
    width: 300px;
    top: 56px;
    left: -300px;
    transition: all 0.1s;
  }
  .catalogueForShow {
    left: 10px;
  }
}
</style>